package app

import (
	"net/url"
	"strings"
	"time"

	uUrl "gitee.com/tomatomeatman/golang-repository/bricks/utils/function/url"
	"github.com/cihub/seelog"
)

type Cloud struct{}

/**
 * 注册服务到注册中心
 */
func (this Cloud) RegistraCloud() {
	if !(AppUtil{}.HasSection("CloudCenter")) {
		return
	}

	cloudCenterSite := AppUtil{}.ReadConfigKey("CloudCenter", "Site", "").(string)
	cloudCenterUser := AppUtil{}.ReadConfigKey("CloudCenter", "User", "").(string)
	cloudCenterPassword := AppUtil{}.ReadConfigKey("CloudCenter", "Password", "").(string)
	DomainName := AppUtil{}.ReadConfigKey("System", "DomainName", "").(string)
	DomainPort := AppUtil{}.ReadConfigKey("System", "DomainPort", "").(string)

	Port := AppUtil{}.ReadConfigKey("System", "Port", "8080").(string)
	Name := AppUtil{}.ReadConfigKey("System", "Name", "").(string)

	var json strings.Builder
	json.WriteString("{\"sSign\":\"")
	json.WriteString(Name)
	json.WriteString("Server\",\"serverPort\":\"")
	json.WriteString(Port)
	json.WriteString("\",\"serverIp\":\"unknown\",\"domainName\":\"")
	json.WriteString(DomainName)
	json.WriteString("\",\"domainPort\":\"")
	json.WriteString(DomainPort)
	json.WriteString("\"}")

	var host strings.Builder
	host.WriteString("http://")
	host.WriteString(cloudCenterSite)
	host.WriteString("/add")

	params := map[string]interface{}{
		"user":       cloudCenterUser,
		"key":        cloudCenterPassword,
		"sSign":      Name + "Server",
		"sLeaveWord": url.QueryEscape(json.String()),
	}

	urlStr := strings.Replace(host.String(), "http://http://", "http://", 1)

	for {
		me := uUrl.HttpUtil{}.DoGet(urlStr, params, nil)
		if me.Gsuccess {
			//fmt.Println("注册服务成功")
			seelog.Info("注册服务成功")
			return
		}

		seelog.Error("注册服务失败,返回内容:", me)
		time.Sleep(time.Second * 5) //休眠5秒
	}
}
